package com.example.amp_test;

import com.rabbitmq.client.*;
import java.sql.*;
import java.sql.Connection;

public class LogConsumer {
    private final static String QUEUE_NAME = "logs_queue";
    private static final String DB_URL = "jdbc:mysql://localhost:3306/logs_db";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        try (com.rabbitmq.client.Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            channel.basicQos(1);

            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), "UTF-8");
                System.out.println("Received: " + message);
                storeLogToDatabase(message);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            };

            channel.basicConsume(QUEUE_NAME, false, deliverCallback, consumerTag -> {});

        }
    }

    private static void storeLogToDatabase(String message) {
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            String sql = "INSERT INTO logs (message) VALUES (?)";
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setString(1, message);
                stmt.executeUpdate();
                System.out.println("Log stored in database: " + message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

